/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.interceptor;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.CookieUtils;
import com.thinkgem.jeesite.common.utils.I18nUtils;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Interceptor that allows for changing the current locale on every request,
 * via a configurable request parameter (default parameter name: "locale").
 *
 * @author Juergen Hoeller
 * @since 20.06.2003
 * @see org.springframework.web.servlet.LocaleResolver
 */
public class LocaleChangeInterceptor extends HandlerInterceptorAdapter {

	/**
	 * Default name of the locale specification parameter: "locale".
	 */
	public static final String DEFAULT_PARAM_NAME = "locale";

	private String paramName = DEFAULT_PARAM_NAME;


	/**
	 * Set the name of the parameter that contains a locale specification
	 * in a locale change request. Default is "locale".
	 */
	public void setParamName(String paramName) {
		this.paramName = paramName;
	}

	/**
	 * Return the name of the parameter that contains a locale specification
	 * in a locale change request.
	 */
	public String getParamName() {
		return this.paramName;
	}


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws ServletException {

		LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
		if(localeResolver == null){
			throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
		}

        String newLocale = request.getParameter(this.paramName);
        if(!StringUtils.isEmpty(newLocale)){
            CookieUtils.setCookie(response, "Locale", newLocale);
			UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
			CacheUtils.remove(DictUtils.CACHE_DICT_MAP);
        }
        else{
            newLocale = CookieUtils.getCookie(request, "Locale");
            if(StringUtils.isEmpty(newLocale)){
                newLocale = Global.CN;
            }
        }

        I18nUtils.setLocaleStr(newLocale);
        request.getSession().setAttribute("Locale", newLocale);

        localeResolver.setLocale(request, response, StringUtils.parseLocaleString(newLocale));

		// Proceed in any case.
		return true;
	}

}